package top.ljjapp.interceptor;/**
 * @FileName: TimeInterceptor.java
 * @Package: top.ljjapp.interceptor
 * @Author: lijiajun
 * <br/>
 * @Created: 2018/11/21 11:22
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * <p></p>
 * <p/>
 * <PRE>
 * <BR> 修改记录
 * <BR>-----------------------------------------------
 * <BR> 修改日期 修改人 修改内容
 * </PRE>
 *
 * @author lijiajun
 */
@Slf4j
@Component
public class TimeInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        log.info("myInterceptor pre");
        log.info( ((HandlerMethod)o).getMethod().getName() );

        httpServletRequest.setAttribute("startTime", new Date().getTime());

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)
            throws Exception {
        log.info("postHandle");
        Long startTime = (Long)httpServletRequest.getAttribute("startTime");
        log.info("time耗时" + (new Date().getTime() - startTime) );
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)
            throws Exception {
        log.info("afterCompletion 不管成功或失败都进来");
        Long startTime = (Long)httpServletRequest.getAttribute("startTime");
        log.info("time耗时" + (new Date().getTime() - startTime) );
        log.info("Exception is " + e);
    }
}